package com.cljz.peipei.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cljz.peipei.R;
import com.cljz.peipei.base.App;
import com.cljz.peipei.base.BaseActivity;
import com.cljz.peipei.model.net.bean.EmojiWordBean;
import com.cljz.peipei.model.net.bean.GetUserInfoBean;
import com.cljz.peipei.model.net.bean.ResponseBean;
import com.cljz.peipei.model.net.bean.TagListBean;
import com.cljz.peipei.present.activity.MainP;
import com.cljz.peipei.ui.adapter.HaveChosenAdapter;
import com.cljz.peipei.utils.CommonUtils;
import com.cljz.peipei.utils.ConstellationUtils;
import com.cljz.peipei.utils.L;
import com.cljz.peipei.utils.T;
import com.cljz.peipei.widget.CameraSurfaceView;
import com.cljz.peipei.widget.FlagButton;
import com.cljz.peipei.widget.PickerViewConstellation;
import com.clzj.peipei.bean.Tag;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.NetUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.router.Router;
import rx.functions.Action1;

/**
 * Created by apple on 2017/4/19.
 */

public class MainActivity extends BaseActivity<MainP> implements EMCallBack, EMConnectionListener, UMShareListener, RadioGroup.OnCheckedChangeListener, FlagButton.OnFlagItemClick, HaveChosenAdapter.OnItemClickListener, EMMessageListener {

    private static final int CALL_WAIT = 233;
    private static final int CUT_EMOJI = 666;
    public static final String AUTO_IGNORE = "autoIgnore";
    public static final String ACCORD_IGNORE = "accordIgnore";
    @BindView(R.id.tv_auto_ignore_where)
    TextView tvAutoIgnoreWhere;
    @BindView(R.id.tv_auto_ignore_back)
    TextView tvAutoIgnoreBack;
    @BindView(R.id.ll_auto_ignore)
    LinearLayout llAutoIgnore;
    @BindView(R.id.dialog_ll)
    LinearLayout dialogLl;

    private String waitType;

    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.iv_label)
    ImageView ivLabel;
    @BindView(R.id.csv_camera)
    CameraSurfaceView csvCamera;
    @BindView(R.id.tv_emoji)
    TextView tvEmoji;
    @BindView(R.id.fl_main)
    FrameLayout flMain;
    @BindView(R.id.ll_see)
    LinearLayout llSee;

    private PopupWindow settingWindow;
    private PopupWindow shareWindow;
    private String seekconstellation;
    private PopupWindow tagsWindow;
    private int matchingSex = 3;
    private HaveChosenAdapter haveChosenAdapter;
    private Handler mainHandler;
    private List<EmojiWordBean.DataBean> emojiWordList;

    private CallReceiver callReceiver;

    private String otherUserId;
    private int autoIgnore = 0;
    private int accordIgnore = 0;
    private long callWaitTime = 10 * 1000;
    //判断是否第一次，进行默认匹配
    private boolean defaultconstellation=true;
    //友盟实现第三方登录
    private UMShareAPI umShareAPI;

    //星座选择
    private RelativeLayout bt_scrollchoose; // 滚动选择器按钮
    private PickerViewConstellation pickerViewConstellation;
    private String[] id;
    private String[] name;
    private RelativeLayout picker_rel; // 选择器布局
    private int constellationIndex = 0;
    private boolean isFirstShowSetting = true;

    //初始化窗口
    @Override
    protected void setScreen() {
        //WindowManager是Android中一个重要的服务（Service ）。WindowManager Service 是全局的，是唯一的
        //WindowManager.LayoutParams 是 WindowManager 接口的嵌套类；它继承于 ViewGroup.LayoutParams；
        // 它用于向WindowManager描述Window的管理策略。
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //窗口显示时，隐藏所有的屏幕装饰（例如状态条）。使窗口占用整个显示区域。
        lp.flags = (WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(lp);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        umShareAPI = UMShareAPI.get(this);
    }

    //// 设置通话界面属性，保持屏幕常亮，关闭输入法，以及解锁
    @Override
    public void initData(Bundle savedInstanceState) {
        initPermission();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        if ("1".equals(getP().getUserInfo(getP().getToken()).getSex())) {
            tvAutoIgnoreWhere.setText("骚年，你到外太空去了？");
        } else {
            tvAutoIgnoreWhere.setText("小仙女，你渡劫去了吗？");
        }
        getP().callEnd();
        getP().emojiWord();
        List<Tag> tags = getP().getTagListForCache();
        beginCallWait(tags);
        mainHandler = new MainHandler(this);

        EMClient.getInstance().login(getP().getUserInfo(getP().getToken()).getUser_id(), getP().getUserInfo(getP().getToken()).getUser_id(), this);
        IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
        callReceiver = new CallReceiver();
        registerReceiver(callReceiver, callFilter);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public MainP newP() {
        return new MainP();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (shareWindow != null && shareWindow.isShowing()) {
            shareWindow.dismiss();
        }
        if (settingWindow != null && settingWindow.isShowing()) {
            settingWindow.dismiss();
        }
        if (tagsWindow != null && tagsWindow.isShowing()) {
            ////关闭popWindow
            tagsWindow.dismiss();
        }
        if (mainHandler != null) {
            mainHandler.removeMessages(CALL_WAIT);
            mainHandler.removeMessages(CUT_EMOJI);
        }
        EMClient.getInstance().chatManager().removeMessageListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mainHandler) {
            //如果参数为null的话，会将所有的Callbacks和Messages全部清除掉。
            //在Acticity退出的时候，可以避免内存泄露。
            mainHandler.removeCallbacksAndMessages(null);
        }
        csvCamera.removeCallbacks(null);
        unregisterReceiver(callReceiver);
        //移除监听
        EMClient.getInstance().chatManager().removeMessageListener(this);
        //同步或异步 进行退出
        EMClient.getInstance().logout(true, this);
    }

    //图标的点击事件
    @Override
    protected void initListener() {
        super.initListener();
        EMClient.getInstance().addConnectionListener(this);
        RxView.clicks(ivSetting)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initSetting();
                    }
                });
        RxView.clicks(ivShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShareWindow();
                    }
                });

        RxView.clicks(ivLabel)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        getP().getTagList();
                    }
                });
        RxView.clicks(tvAutoIgnoreBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        llAutoIgnore.setVisibility(View.GONE);
                        ivLabel.setVisibility(View.VISIBLE);
                        llSee.setVisibility(View.VISIBLE);
                        if (mainHandler != null) {
                            mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 0);
                            mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                        }
                    }
                });
    }

    //设置标签
    private void initTags(final List<TagListBean.DataBean.tagBean> otherTagList, final List<Tag> tags) {
        View tagsView = LayoutInflater.from(this).inflate(R.layout.pop_tags, null);
        RecyclerView rvHaveChosen = (RecyclerView) tagsView.findViewById(R.id.rv_have_chosen);
        FlagButton fbTags = (FlagButton) tagsView.findViewById(R.id.fb_tags);
        FrameLayout flClose = (FrameLayout) tagsView.findViewById(R.id.fl_close);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvHaveChosen.setLayoutManager(linearLayoutManager);
        final HaveChosenAdapter haveChosenAdapter = new HaveChosenAdapter(this);
        haveChosenAdapter.setMyTagList(tags);
        rvHaveChosen.setAdapter(haveChosenAdapter);
        tagsWindow = new PopupWindow(tagsView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        tagsWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        tagsWindow.setBackgroundDrawable(dw);
        tagsWindow.showAtLocation(csvCamera, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        List<String> tagList = new ArrayList<>();
        if (otherTagList != null) {
            for (int i = 0; i < otherTagList.size(); i++) {
                tagList.add(otherTagList.get(i).getTag_name());
            }
            fbTags.initChildViews(tagList, new FlagButton.OnFlagItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (haveChosenAdapter.myTagList.size() >= 3) {
                        T.getInstance().showShort("最多可以添加三个标签哦");
                    } else {
                        if (!haveChosenAdapter.contains(otherTagList.get(position))) {
                            TagListBean.DataBean.tagBean tagBean = otherTagList.get(position);
                            Tag tag = new Tag(tagBean.getId(), tagBean.getTag_name());
                            haveChosenAdapter.addTag(tag);
                            getP().tagSet(otherTagList.get(position).getId(),tag);
                        } else {
                            T.getInstance().showShort("已添加过该标签");
                        }
                    }
                }
            });
        }
        //上面跑完了，下面重新载入
        RxView.clicks(flClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        tagsWindow.dismiss();
                    }
                });
        haveChosenAdapter.setOnItemClickListener(new HaveChosenAdapter.OnItemClickListener() {
            @Override
            public void onClick(Tag dataBean) {
                haveChosenAdapter.removeTag(dataBean);
                getP().tagDel(dataBean.getId(),dataBean);
            }

            @Override
            public void onLongClick(Tag dataBean) {

            }
        });
    }

    /**
     * 加载分享popupWindow
     */
    private void initShareWindow() {
        View shareView = LayoutInflater.from(this).inflate(R.layout.pop_share, null);
        LinearLayout llQQShare = (LinearLayout) shareView.findViewById(R.id.ll_qq_share);
        LinearLayout llZoneShare = (LinearLayout) shareView.findViewById(R.id.ll_zone_share);
        if (shareWindow == null) {
            shareWindow = new PopupWindow();
        }
        shareWindow.setContentView(shareView);
        shareWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        shareWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        shareWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        shareWindow.setFocusable(true);
        shareWindow.setOutsideTouchable(true);
        shareWindow.setTouchable(true);
        //更新PopupWindow状态，如果当前已是显示状态，就从当前状态更新
        shareWindow.update();
        shareWindow.showAsDropDown(ivShare, Kits.Dimens.dpToPxInt(this, -55), Kits.Dimens.dpToPxInt(this, 10));
        RxView.clicks(llQQShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShare(SHARE_MEDIA.QQ);
                    }
                });
        RxView.clicks(llZoneShare)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        initShare(SHARE_MEDIA.QZONE);
                    }
                });

    }


    private void initShare(SHARE_MEDIA media) {
        UMWeb shareWeb = new UMWeb(getP().getUserInfo(getP().getToken()).getDownload());
        shareWeb.setTitle("PeiPei");
        shareWeb.setDescription("随时随地发现有缘人");
        new ShareAction(this)
                .setPlatform(media)
                .setCallback(this)
                .withMedia(shareWeb)
                .share();
        shareWindow.dismiss();
    }

    /**
     * 加载设置左上角popupWindow
     */
    private void initSetting() {
        View settingView = LayoutInflater.from(this).inflate(R.layout.pop_setting, null);
        ImageView ivClose = (ImageView) settingView.findViewById(R.id.iv_close);
        RelativeLayout rlReturn = (RelativeLayout) settingView.findViewById(R.id.rl_return);
        RelativeLayout rlSex = (RelativeLayout) settingView.findViewById(R.id.rl_sex);
        RadioGroup rgSex = (RadioGroup) settingView.findViewById(R.id.rg_sex);
        FrameLayout flClose = (FrameLayout) settingView.findViewById(R.id.fl_close);

        final LinearLayout llconstellation = (LinearLayout) settingView.findViewById(R.id.ll_constellation);
        RelativeLayout rlconstellation = (RelativeLayout) settingView.findViewById(R.id.rl_constellation);
        final TextView tvConstellation = (TextView) settingView.findViewById(R.id.tv_set_constellation);
        RelativeLayout rlExit = (RelativeLayout) settingView.findViewById(R.id.rl_exit);
        final RelativeLayout rlExitLayout = (RelativeLayout) settingView.findViewById(R.id.rl_exit_layout);
        View btn_cancle = rlExitLayout.findViewById(R.id.btn_cancel);
        View btn_exit = rlExitLayout.findViewById(R.id.btn_exit);
        settingWindow = new PopupWindow(settingView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        settingWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        settingWindow.setBackgroundDrawable(dw);
        settingWindow.showAtLocation(csvCamera, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        RxView.clicks(flClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        settingWindow.dismiss();
                    }
                });
        RxView.clicks(ivClose)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        settingWindow.dismiss();
                    }
                });
        RxView.clicks(rlReturn)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.newIntent((Activity) App.getInstance())
                                .to(SetSexActivity.class)
                                .launch();
                        settingWindow.dismiss();
                    }
                });
        RxView.clicks(rlExit)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (rlExitLayout.getVisibility() == View.VISIBLE){
                            rlExitLayout.setVisibility(View.GONE);
                        }else {
                            rlExitLayout.setVisibility(View.VISIBLE);
                        }
                    }
                });
        RxView.clicks(btn_cancle)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        rlExitLayout.setVisibility(View.GONE);
                    }
                });
        RxView.clicks(btn_exit)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        getP().exit(getP().getToken());
                        loginOvertime(EXIT);
                        Router.pop(MainActivity.this);
                    }
                });
        //选择星座
//        if (defaultconstellation){
//            //初次进入匹配类型
//            tvConstellation.setText(ConstellationUtils.getCouple(Integer.valueOf(getP().getUserInfo(getP().getToken()).getConstellation())));
//            defaultconstellation=false;
//        }else{
            RxView.clicks(rlconstellation)
                    .compose(this.<Void>bindToLifecycle())
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            dialogLl.setVisibility(View.VISIBLE);
                            settingWindow.dismiss();
                            TextView datetvselect = (TextView) findViewById(R.id.date_tv_select);//确定
                            TextView constellationtvcancel = (TextView)findViewById(R.id.constellation_tv_cancel);//取消
                            final PickerViewConstellation personconstellationpv= (PickerViewConstellation) findViewById(R.id.person_constellation_pv);
                            datetvselect.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //这里是要和服务器做绑定的
                                    constellationIndex = personconstellationpv.getmCurrentSelected();
//                                tvConstellation.setText(PickerViewConstellation.name[constellationIndex]);
                                    tvConstellation.setText(ConstellationUtils.getConstellation(constellationIndex+1));
                                    L.e("mag",""+ConstellationUtils.getConstellation(constellationIndex+1));
                                    dialogLl.setVisibility(View.GONE);
                                    isFirstShowSetting = false;
                                }
                            });
                            constellationtvcancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialogLl.setVisibility(View.GONE);
                                }
                            });
                        }
                    });

 //       }
        rgSex.setOnCheckedChangeListener(this);
        tvConstellation.setText(ConstellationUtils.getConstellation(constellationIndex+1));
        if (isFirstShowSetting){
            tvConstellation.setVisibility(View.GONE);
        }
    }


    @Override
    public void onSuccess() {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
        EMClient.getInstance().chatManager().addMessageListener(this);
        L.e("main", "登录聊天服务器成功！");
    }

    @Override
    public void onError(int i, String s) {
        L.e("main", "登录聊天服务器失败！");
    }

    @Override
    public void onProgress(int i, String s) {

    }

    @Override
    public void onConnected() {

    }

    @Override
    public void onDisconnected(final int error) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (error == EMError.USER_REMOVED) {
                    // 显示帐号已经被移除
                    L.e("main", "帐号已经被移除！");
                } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                    // 显示帐号在其他设备登录
                    L.e("main", "帐号在其他设备登录！");
                } else if (NetUtils.hasNetwork(MainActivity.this)) {
                    //连接不到聊天服务器
                    L.e("main", "连接不到聊天服务器！");
                } else {
                    //当前网络不可用，请检查网络设置
                    L.e("main", "当前网络不可用，请检查网络设置！");
                }
            }
        });
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        shareResult(share_media, "分享成功");

    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        shareResult(share_media, "分享失败");

    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        shareResult(share_media, "取消分享");

    }

    private void shareResult(SHARE_MEDIA share_media, String msg) {
        if (SHARE_MEDIA.QQ.equals(share_media)) {
            T.getInstance().showShort("QQ" + msg);
        } else if (SHARE_MEDIA.QZONE.equals(share_media)) {
            T.getInstance().showShort("QQ空间" + msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 30) {
            getP().callEnd();
            EMClient.getInstance().chatManager().addMessageListener(this);
            csvCamera.setVisibility(View.VISIBLE);
            String result = "";
            if (data != null) {
                result = data.getStringExtra("result");
                L.e("data:" + data.getStringExtra("result"));
            }
            L.e("result:" + result);

            if (AUTO_IGNORE.equals(result)) {
                autoIgnore++;
                if (autoIgnore >= 2) {
                    llAutoIgnore.setVisibility(View.VISIBLE);
                    ivLabel.setVisibility(View.GONE);
                    llSee.setVisibility(View.GONE);
                } else {
                    if (mainHandler != null) {
                        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 0);
                        mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                    }
                }
            } else if (ACCORD_IGNORE.equals(result)) {
                accordIgnore++;
                if (accordIgnore == 3) {
                    callWaitTime = 30 * 1000;

                    if (mainHandler != null) {
                        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, callWaitTime);
                        mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                    }
                } else if (accordIgnore >= 4) {
                    callWaitTime = callWaitTime * 2;
                    if (mainHandler != null) {
                        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, callWaitTime);
                        mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                    }
                } else {
                    mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 0);
                    mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                }
            } else {
                if (mainHandler != null) {
                    mainHandler.sendEmptyMessageDelayed(CALL_WAIT, 0);
                    mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 1000);
                }
            }

        }
    }

    public void getUserInfoSucceed(GetUserInfoBean getUserInfoBean) {
//        mainHandler=new MainHandler(this);
//        seekconstellation=getUserInfoBean.getData().getConstellation();


    }


    public void getUserInfoFail(String error) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_girl:
                matchingSex = 2;
                break;
            case R.id.rb_boy:
                matchingSex = 1;
                break;
            case R.id.rb_all:
                matchingSex = 3;
                break;
        }
    }

    public void getTagListSucceed(TagListBean tagListBean,List<Tag> tags) {
        initTags(tagListBean.getData().getOther(),tags);
    }

    //开始等待
    public void beginCallWait(List<Tag> tags) {
        int size = tags.size();
        if (size > 0) {
            StringBuilder myTags = new StringBuilder();
            for (int i = 0; i < size; i++) {
                myTags.append(tags.get(i).getId());
                if (size - 1 != i) {
                    myTags.append(",");
                }
            }
            getP().callWait(matchingSex, myTags.toString(),constellationIndex+1);
        } else {
            getP().callWait(matchingSex, "", constellationIndex+1);
        }
    }


    public void getTagListFail(String error) {

    }

    public void getTagSetSucceed(ResponseBean responseBean) {

    }

    public void getTagSetFail(String error) {

    }

    public void getTagDelSucceed(ResponseBean responseBean) {

    }

    public void getTagDelFail(String error) {

    }

    //等待60秒换句子
    public void getEmojiWordSucceed(EmojiWordBean emojiWordbean) {
        emojiWordList = emojiWordbean.getData();
        if (emojiWordList.size() != 0) {
            mainHandler.sendEmptyMessageDelayed(CUT_EMOJI, 10000);
            tvEmoji.setText(emojiWordList.get(0).getContent());
        }
    }

    public void getEmojiWordFail(String error) {

    }

    public TextView getTvEmoji() {
        return tvEmoji;
    }

    public List<EmojiWordBean.DataBean> getEmojiWordList() {
        return emojiWordList;
    }

    //呼叫等待10秒匹配成功
    public void callWaitSucceed(ResponseBean responseBean) {
        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, callWaitTime);
        L.e("msg", "等待成功" + System.currentTimeMillis());
    }

    public void callWaitFail(String error) {
        mainHandler.sendEmptyMessageDelayed(CALL_WAIT, callWaitTime);
        L.e("msg", "等待成功" + System.currentTimeMillis());

    }

    //挂断，开始调用自己的接口====不能成功在忽略后10秒再次调用
    public void callEndSucceed(ResponseBean responseBean) {
        L.e("msg", "挂断成功");
    }

    public void callEndFail(String error) {

    }


    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        //收到消息
        L.e("收到消息");
    }

    //透传消息这里进行10秒的重新匹配
    @Override
    public void onCmdMessageReceived(final List<EMMessage> messages) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                L.e("收到透传消息");
                for (int i = 0; i < messages.size(); i++) {
                    L.e(messages.get(i).getBody().toString());
                }
                String cmd = CommonUtils.getNumbers(messages.get(0).getBody().toString());
                if (cmd.length() == 5) {
                    otherUserId = cmd;
                    waitType = "invite";
                    Router.newIntent((Activity) App.getInstance())
                            .putString("userId", otherUserId)
                            .putString("from", waitType)
                            .requestCode(30)
                            .to(VideoCallActivity.class)
                            .anim(R.anim.in, R.anim.out)
                            .launch();
                    //判断是接收方还是发起方
                }
            }
        });
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        L.e("收到已读回执");
        //收到已读回执
    }

    @Override
    public void onMessageDelivered(List<EMMessage> message) {
        //收到已送达回执
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
        //消息状态变动
        L.e("消息状态变动");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onClick(Tag dataBean) {

    }

    @Override
    public void onLongClick(Tag dataBean) {

    }

    @Override
    public void onItemClick(int position) {

    }


    private static class MainHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;
        private int position = 1;
        List<EmojiWordBean.DataBean> emojiWordBeenList;

        MainHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
            emojiWordBeenList = activity.getEmojiWordList();
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case CUT_EMOJI:
                    if (emojiWordBeenList != null) {
                        if (position >= emojiWordBeenList.size() - 1) {
                            position = 0;
                        }
                        activity.getTvEmoji().setText(emojiWordBeenList.get(position).getContent());
                        this.sendEmptyMessageDelayed(CUT_EMOJI, 60000);
                        position++;
                    }
                    break;
                case CALL_WAIT:
                    List<Tag> tags = activity.getP().getTagListForCache();
                    activity.beginCallWait(tags);
                    break;

            }
        }
    }


    private class CallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 拨打方username
            String from = intent.getStringExtra("from");
            // call type
            String type = intent.getStringExtra("type");
            //跳转到通话页面
            L.e(from);
            waitType = "receive";
            Router.newIntent((Activity) App.getInstance())
                    .putString("userId", from)
                    .putString("from", waitType)
                    .requestCode(30)
                    .to(VideoCallActivity.class)
                    .anim(R.anim.in, R.anim.out)
                    .launch();
        }
    }


}
